define(['WebPDF'], function(WebPDF) {
	WebPDF.directive('pdfPage', [function() {
		'use strict';
		function updateLayout($scope, element) {	
			var position = $scope.layout.LayoutPageView($scope.page, $scope.scale, $scope.docViewWidth);					
			element.css(position);		
		}		
		return {
			restrict: 'AE',
			replace : true,		
			require : '^?pdfDoc',	
			templateUrl: 'js/pdfview/tpl/pdfpage.html',
			controller : 'PDFPageController',			
			compile: function(element, attr) {
				return{					
					post : function($scope, element, attr, PDFDocController) {						
						$scope.$watchGroup(['scale','docViewWidth'], function(newValue, oldValue) {					 	
					 		if (newValue === oldValue) return;		
					 		updateLayout($scope, element);
					 	});		

						var imageUrlWatch = $scope.$watch('page.imageUrl', function(newValue){					 		
							if (!newValue) return;
							element.children(".fwr-page-bg-image").load(function(){
								WebPDF.PageShowCompleted({'pageView' : element, 'pdfPage': $scope.page});
							}).attr("src", $scope.page.imageUrl);
							imageUrlWatch();
						});	

						element.attr("pageIndex", $scope.page.pageIndex);								
						updateLayout($scope, element);				
						element.one("loadpage", $scope.loadPage);
						$scope.pageVisible = true;
						element.on("page-visible-changed", function(event, data) {
							if (data.visible){
								console.log('page-visible-changed', $scope.page.pageIndex, data.visible);
							}
							if ($scope.pageVisible  !=  data.visible){
								$scope.$evalAsync(function(){
									$scope.pageVisible = data.visible;
								});
							}				

						});						
						PDFDocController.pageViewCreated();											
					}
				};
			},

		};
	}]);
});